package cn.com.libertymutual.sp.service.impl;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Lists;

import cn.com.libertymutual.core.security.encoder.Md5PwdEncoder;
import cn.com.libertymutual.core.util.Constants;
import cn.com.libertymutual.core.util.Current;
import cn.com.libertymutual.core.util.ListUtil;
import cn.com.libertymutual.core.web.ServiceResult;
import cn.com.libertymutual.sp.bean.TbSpAuthority;
import cn.com.libertymutual.sp.bean.TbSpRankChange;
import cn.com.libertymutual.sp.bean.TbSpStoreConfig;
import cn.com.libertymutual.sp.bean.TbSpStoreProduct;
import cn.com.libertymutual.sp.bean.TbSpTopChannelAuthProduct;
import cn.com.libertymutual.sp.bean.TbSpUser;
import cn.com.libertymutual.sp.dao.AuthorityDao;
import cn.com.libertymutual.sp.dao.StoreProductDao;
import cn.com.libertymutual.sp.dao.TbSpRankChangeDao;
import cn.com.libertymutual.sp.dao.TopChannelAuthProductDao;
import cn.com.libertymutual.sp.dao.UserDao;
import cn.com.libertymutual.sp.dto.UserDto;
import cn.com.libertymutual.sp.req.StoreRateReq;
import cn.com.libertymutual.sp.service.api.LevelService;
import cn.com.libertymutual.sp.service.api.UserService;
import cn.com.libertymutual.sys.bean.SysBranch;
import cn.com.libertymutual.sys.bean.SysRoleUser;
import cn.com.libertymutual.sys.bean.SysUser;
import cn.com.libertymutual.sys.dao.ISysRoleUserDao;
import cn.com.libertymutual.sys.dao.ISysUserDao;
import cn.com.libertymutual.sys.dao.SysBranchDao;

@Service("levelService")
public class LevelServiceImpl implements LevelService {

	private Logger log = LoggerFactory.getLogger(getClass());
	@Autowired
	private SysBranchDao sysBranchDao;
	@Autowired
	private TbSpRankChangeDao rankChangeDao;
	@Autowired
	private TopChannelAuthProductDao topChannelAuthProductDao;
	@Autowired
	private UserDao userDao;
	@Autowired
	private StoreProductDao storeProductDao;
	@Autowired
	private UserService userService;
	@Autowired
	private AuthorityDao authorityDao;
	@Autowired
	private NamedParameterJdbcTemplate readJdbcTemplate2;
	@Autowired
	private ISysUserDao iSysUserDao;
	@Autowired
	private ISysRoleUserDao roleUserDao;

	@Override
	public ServiceResult levelList(String branchNo, String branchCname) {
		ServiceResult sr = new ServiceResult();
		List<SysBranch> branchs = sysBranchDao.findByLevel("1");
		if (CollectionUtils.isNotEmpty(branchs)) {
			branchRecursive(branchs);
		}
		sr.setResult(branchs);
		return sr;
	}

	public List<SysBranch> branchRecursive(List<SysBranch> branchp) {

		List<SysBranch> branchs = Lists.newArrayList();
		for (SysBranch branchP : branchp) {
			log.info(branchP.getBranchCname());
			branchs = sysBranchDao.findNextBranch(branchP.getBranchNo());
			if (CollectionUtils.isNotEmpty(branchs)) {
				branchP.setNextBranch(branchs);
				branchRecursive(branchs);
			} else {
				continue;
			}
		}
		return branchp;
	}

	@Override
	public ServiceResult isMergeUser(String mobile, String comCode) {
		ServiceResult sr = new ServiceResult();
		List<TbSpUser> users = userDao.findByMobile(mobile);
		if (CollectionUtils.isNotEmpty(users)) {// 以前存在的用户，需要合并更新
			for (TbSpUser user : users) {
				if (StringUtils.isNotBlank(comCode) && (comCode.startsWith("WX") || comCode.startsWith("BS"))) {
					TbSpUser comUser = userDao.findByUserCode(comCode);
					user.setAgrementNo(comUser.getAgrementNo());
				}
				user.setRole(roleUserDao.findByUserid(user.getUserCode()));
				user.setSysUser(iSysUserDao.findByUserCode(user.getUserCode()));
			}
			sr.setSuccess();
			sr.setResult(users.get(0));
			return sr;
		}
		List<SysUser> dbsysuser = iSysUserDao.findByMobile(mobile);
		if (CollectionUtils.isNotEmpty(dbsysuser)) {
			sr.setSuccess();
			sr.setResult(dbsysuser.get(0));
			return sr;
		}

		sr.setSuccess();
		return sr;
	}
	
	//根据comCode递归查找二级机构
	private List<String> findSecondBranch(String code,List<String> twobs) {
		if(code.startsWith("BS")||code.startsWith("WX")) {
			TbSpUser upUser = userDao.findByUserCode(code);
			if (StringUtils.isNotBlank(upUser.getComCode())) {
				findSecondBranch(upUser.getComCode(), twobs);
			}
		}else if(null!=code){//机构码
			SysBranch branch = sysBranchDao.findByBranchNo(code);
			if(null!=branch) {
				if ("2".equals(branch.getBranchLevel())) {
					twobs.add(branch.getBranchNo());
				}else {
					findSecondBranch(branch.getUpperBranchNo(), twobs);
				}
			}
		}
		return twobs;
	}

	@Transactional
	@Override
	public ServiceResult createChannelUser(UserDto userDto) {
		userDto.setCanScore(Constants.FALSE);
		ServiceResult sr = new ServiceResult();
		try {
			Md5PwdEncoder md5PwdEncoder = new Md5PwdEncoder();
			TbSpUser spUser = null;
			List<TbSpUser> users = userDao.findByMobile(userDto.getMobile());
			if (CollectionUtils.isNotEmpty(users)) {// 以前存在的用户，需要合并更新
				spUser = users.get(0);
				if (Constants.TRUE.equals(userDto.getIdType())) {
					List<TbSpUser> dbusers = userDao.findByIdNumber(userDto.getIdNumber());
					for (TbSpUser u : dbusers) {
						if (Constants.USER_REGISTER_TYPE_0.equals(u.getRegisterType())) {
							if (u.getId().compareTo(spUser.getId()) != 0
									&& userDto.getIdNumber().equals(u.getIdNumber())) {
								sr.setFail();
								sr.setResult("您输入的证件号码已被认证!");
								return sr;
							}
						}
					}
				}
				if (StringUtils.isNotBlank(userDto.getAgrementNo())) {
					if (StringUtils.isNotBlank(spUser.getAgrementNo())
							&& !spUser.getAgrementNo().equals(userDto.getAgrementNo())) {
						String userType = "2";// 默认普通账户 // 已废弃：this.getUserType(orgCode, licenceNo, accType, codeType);
						// // 有代理人代码和名称的算中介协议，余下的算CA协议
						if (StringUtils.isNotBlank(userDto.getAgrementName())) {
							userType = "3";// 专业代理
						} else {
							// CA协议
							if (StringUtils.isNotBlank(userDto.getOrgCode())
									|| StringUtils.isNotBlank(userDto.getLicenceNo())) {
								userType = "4";// 商户
							} else {
								userType = "5";// 销售人员
								// 目前临时措施 ，无积分
								sr.setFail();
								sr.setResult("当前不支持渠道赠送积分,请更换业务关系代码!");
								return sr;
							}
						}
						userDto.setUserType(userType);
						// 修改其所有子集的业务关系代码
						List<TbSpUser> nextChannels = userDao.findByComCode(spUser.getUserCode());
						if (CollectionUtils.isNotEmpty(nextChannels)) {
							updateNextAgreementNo(userDto, spUser, nextChannels);
						}
						spUser.setChannelCode(userDto.getChannelCode());
						spUser.setChannelName(userDto.getChannelName());
						spUser.setChannelType(userDto.getCustomerType());
						spUser.setCustomName(userDto.getCustomerName());
						spUser.setSaleCode(userDto.getSaleCode());
						spUser.setSaleName(userDto.getSaleName());
						spUser.setAgrementNo(userDto.getAgrementNo());
						spUser.setAgrementName(userDto.getAgrementName());
						List<String> twobs = Lists.newArrayList();
						List<String> backtwobs = findSecondBranch(userDto.getComCode(),twobs);
						if (CollectionUtils.isNotEmpty(backtwobs)) {
							spUser.setBranchCode(backtwobs.get(0));
						}
//						spUser.setBranchCode(userDto.getBranchCode());
						spUser.setAreaCode(null);
						spUser.setAreaName(null);
						spUser.setUserType(userType);
					}
					// if (!userDto.getComCode().startsWith("WX") &&
					// !userDto.getComCode().startsWith("BS")) {
					// spUser.setChannelCode(userDto.getChannelCode());
					// spUser.setChannelName(userDto.getChannelName());
					// spUser.setChannelType(userDto.getCustomerType());
					// spUser.setCustomName(userDto.getCustomerName());
					// spUser.setSaleCode(userDto.getSaleCode());
					// spUser.setSaleName(userDto.getSaleName());
					// spUser.setAgrementNo(userDto.getAgrementNo());
					// spUser.setBranchCode(userDto.getBranchCode());
					// spUser.setAreaCode(null);
					// spUser.setAreaName(null);
					// String userType = "2";// 默认普通账户 // 已废弃：this.getUserType(orgCode, licenceNo,
					// accType, codeType);
					// // 有代理人代码和名称的算中介协议，余下的算CA协议
					// if (StringUtils.isNotBlank(userDto.getAgrementName())) {
					// userType = "3";// 专业代理
					// } else {
					// // CA协议
					// if (StringUtils.isNotBlank(userDto.getOrgCode()) ||
					// StringUtils.isNotBlank(userDto.getLicenceNo())) {
					// userType = "4";// 商户
					// } else {
					// userType = "5";// 销售人员
					// }
					// }
					// spUser.setUserType(userType);
					// } else {
					// List<String> userCodes = Lists.newArrayList();
					// // 找到最顶层渠道
					// List<String> list = this.topUser(userDto.getComCode(), userCodes);
					// TbSpUser topUser = userDao.findByUserCode(list.get(list.size() - 1));
					// spUser.setBranchCode(topUser.getBranchCode());
					// spUser.setAreaCode(topUser.getBranchCode());
					// String userType = "2";// 默认普通账户 // 已废弃：this.getUserType(orgCode, licenceNo,
					// accType, codeType);
					// if (!topUser.getAgrementNo().equals(userDto.getAgrementNo())) {//
					// 与顶级业务关系代码不一样，入库
					// spUser.setChannelCode(userDto.getChannelCode());
					// spUser.setChannelName(userDto.getChannelName());
					// spUser.setChannelType(userDto.getCustomerType());
					// spUser.setCustomName(userDto.getCustomerName());
					// spUser.setSaleCode(userDto.getSaleCode());
					// spUser.setSaleName(userDto.getSaleName());
					// spUser.setAgrementNo(userDto.getAgrementNo());
					// spUser.setBranchCode(userDto.getBranchCode());
					// spUser.setAreaCode(null);
					// spUser.setAreaName(null);
					// // 有代理人代码和名称的算中介协议，余下的算CA协议
					// if (StringUtils.isNotBlank(userDto.getAgrementName())) {
					// userType = "3";// 专业代理
					// } else {
					// // CA协议
					// if (StringUtils.isNotBlank(userDto.getOrgCode()) ||
					// StringUtils.isNotBlank(userDto.getLicenceNo())) {
					// userType = "4";// 商户
					// } else {
					// userType = "5";// 销售人员
					// }
					// }
					// } else {
					// spUser.setChannelCode(null);
					// spUser.setChannelName(null);
					// spUser.setChannelType(null);
					// spUser.setCustomName(null);
					// spUser.setSaleCode(null);
					// spUser.setSaleName(null);
					// spUser.setAgrementName(null);
					// spUser.setAgrementNo(null);
					// }
					// spUser.setUserType(userType);
					// }
				}
				if (StringUtils.isNotBlank(userDto.getPassword())) {
					spUser.setPassword(md5PwdEncoder.encodePassword(userDto.getPassword()));
				}
				spUser.setComCode(userDto.getComCode());
				spUser.setIdType(userDto.getIdType());
				spUser.setBaseRate(userDto.getBaseRate());
				// spUser.setCanModify(userDto.getCanModify());
				// if (!userDto.getComCode().startsWith("WX") &&
				// !userDto.getComCode().startsWith("BS")) {
				// spUser.setCanModify(Constants.TRUE);
				// }else {
				spUser.setCanModify(Constants.FALSE);
				// }
				spUser.setUserName(userDto.getUserRealName());
				spUser.setCanScore(userDto.getCanScore());
				spUser.setEmployeeCode(userDto.getEmployeeCode());
				spUser.setUpUserCode(userDto.getUpUserCode());
				spUser.setShopName(userDto.getShopName());
				spUser.setIdNumber(userDto.getIdNumber());
				spUser.setRegisterType("1");
				spUser.setStoreFlag("1");
				spUser = userDao.save(spUser);
			} else {
				if (StringUtils.isNotBlank(userDto.getUpUserCode())) {
					TbSpUser upUser = userDao.findByUserCode(userDto.getUpUserCode());
					if (null == upUser) {
						sr.setFail();
						sr.setResult("未找到关系上属人员!");
						return sr;
					}
				}
				// 临时措施，
				if (StringUtils.isNotBlank(userDto.getAgrementNo())) {
					// 如果修改了业务关系代码
					if (StringUtils.isBlank(userDto.getAgrementName()) && StringUtils.isBlank(userDto.getOrgCode())
							&& StringUtils.isBlank(userDto.getLicenceNo())) {
						// 临时措施，不送积分
						sr.setFail();
						sr.setResult("当前不支持渠道赠送积分,请更换业务关系代码!");
						return sr;
					}
				}
				if (Constants.TRUE.equals(userDto.getIdType())) {
					List<TbSpUser> dbusers = userDao.findByIdNumber(userDto.getIdNumber());
					if (CollectionUtils.isNotEmpty(dbusers)) {
						for (TbSpUser u : dbusers) {
							if (!Constants.USER_REGISTER_TYPE_1.equals(u.getRegisterType())) {
								if (userDto.getIdNumber().equals(u.getIdNumber())) {
									sr.setFail();
									sr.setResult("您输入的证件号码已被认证!");
									return sr;
								}
							}
						}
					}
				}
				userDto.setRegisterType("1");// 1=后台注册(渠道用户)
				if (StringUtils.isNotBlank(userDto.getUserRealName())) {
					userDto.setUserName(userDto.getUserRealName());
				}
				// if (StringUtils.isNotBlank(userDto.getAgrementNo())) {
				// if (userDto.getComCode().startsWith("WX") ||
				// userDto.getComCode().startsWith("BS")) {
				// List<String> userCodes = Lists.newArrayList();
				// // 找到最顶层渠道
				// List<String> list = this.topUser(userDto.getComCode(), userCodes);
				// TbSpUser topUser = userDao.findByUserCode(list.get(list.size() - 1));
				// userDto.setBranchCode(topUser.getBranchCode());
				// if (topUser.getAgrementNo().equals(userDto.getAgrementNo())) {// 与顶级业务关系代码一样
				// userDto.setChannelCode(null);
				// userDto.setChannelName(null);
				// userDto.setCustomerType(null);
				// userDto.setCustomerName(null);
				// userDto.setSaleCode(null);
				// userDto.setSaleName(null);
				// userDto.setAgrementName(null);
				// userDto.setAgrementNo(null);
				// }
				// }
				// }
				userDto.setCanModify(Constants.FALSE);
				List<String> twobs = Lists.newArrayList();
				List<String> backtwobs = findSecondBranch(userDto.getComCode(),twobs);
				if (CollectionUtils.isNotEmpty(backtwobs)) {
					userDto.setBranchCode(backtwobs.get(0));
				}
				spUser = userService.createFrontChannelUser(userDto);
				List<String> userCodes = Lists.newArrayList();
				List<String> list = this.topUser(spUser.getComCode(), userCodes);
				if (CollectionUtils.isNotEmpty(list)) {
					TbSpUser topuser = userDao.findByUserCode(list.get(list.size() - 1));
					// 看是否有授权产品
					List<TbSpTopChannelAuthProduct> proList = topChannelAuthProductDao
							.findByUserCode(topuser.getUserCode());
					if (CollectionUtils.isNotEmpty(proList)) {
						int serialNo = 1;
						for (TbSpTopChannelAuthProduct tp : proList) {
							TbSpStoreProduct storep = new TbSpStoreProduct();
							storep.setIsShow(Constants.TRUE);
							storep.setProductId(tp.getProductId());
							storep.setRiskSerialNo(serialNo);
							storep.setSerialNo(serialNo);
							storep.setUserCode(spUser.getUserCode());
							storeProductDao.save(storep);
							serialNo++;
						}
					}
				}
			}
			SysUser sysUser = new SysUser();
			SysRoleUser role = null;
			List<SysUser> dbsysuser = iSysUserDao.findByMobile(userDto.getMobile());
			if (CollectionUtils.isNotEmpty(dbsysuser)) {
				sr.setFail();
				sr.setResult("该手机号已经被使用！");
				return sr;
			} else {// 新建后台用户
				role = new SysRoleUser();
				role.setRoleid(userDto.getRoleType());
				sysUser = new SysUser();
				sysUser.setLoginnum(0);
				sysUser.setStatus("1");
				sysUser.setType(userDto.getType());
				sysUser.setClevel(userDto.getRoleType().toString());
				sysUser.setRoleCode(userDto.getRoleType().toString());
				sysUser.setStatus("1");
				sysUser.setCreated(Current.date.get());
				sysUser.setCreater(Current.userId.get());
				sysUser.setPassword(md5PwdEncoder.encodePassword(userDto.getPassword()));
				sysUser.setMobileno(userDto.getMobile());
				// 所属机构
				if (StringUtils.isNotBlank(userDto.getComCode())
						&& (userDto.getComCode().startsWith("WX") || userDto.getComCode().startsWith("BS"))) {
					List<String> userCodes = Lists.newArrayList();
					List<String> list = findTopBranchNo(userDto.getComCode(), userCodes);
					SysBranch branch = sysBranchDao.findByBranchNo(list.get(list.size() - 1));
					sysUser.setBranchcode(branch.getBranchNo());
					sysUser.setBranchName(branch.getBranchCname());
				} else if (StringUtils.isNotBlank(userDto.getComCode())) {
					SysBranch branch = sysBranchDao.findByBranchNo(userDto.getComCode());
					sysUser.setBranchcode(branch.getBranchNo());
					sysUser.setBranchName(branch.getBranchCname());
				}
				if (StringUtils.isNotBlank(userDto.getType()) && StringUtils.isNotBlank(userDto.getUserName())
						&& Constants.FALSE.equals(userDto.getType())) {
					role.setUserid(userDto.getUserName());
					sysUser.setUserid(userDto.getUserName());
					sysUser.setUsername(userDto.getUserName());
					sysUser.setUserCode(spUser.getUserCode());
				} else {
					role.setUserid(spUser.getUserCode());
					sysUser.setUserid(spUser.getUserCode());
					sysUser.setUsername(userDto.getUserRealName());
					sysUser.setUserCode(spUser.getUserCode());
				}
			}
			roleUserDao.save(role);
			iSysUserDao.save(sysUser);
			// // 配置用户订单查询权限
			// if (Constants.TRUE.equals(userDto.getDefaultAuth())) {
			// TbSpAuthority newAuth = new TbSpAuthority();
			// newAuth.setChannelCode(spUser.getUserCode());
			// newAuth.setCreateTime(new Date());
			// newAuth.setUserCode(spUser.getUserCode());
			// newAuth.setStatus(Constants.TRUE);
			// authorityDao.save(newAuth);
			// }
		} catch (Exception e) {
			e.printStackTrace();
			sr.setAppFail();
			sr.setResult("创建渠道用户失败！");
			return sr;
		}
		sr.setSuccess();
		return sr;
	}

	@Transactional
	@Override
	public ServiceResult updateChannelUser(UserDto userDto) {
		userDto.setCanScore(Constants.FALSE);
		ServiceResult sr = new ServiceResult();
		try {
			TbSpUser spComUser = userDao.findByUserCode(userDto.getComCode());
			SysBranch branch = sysBranchDao.findByBranchNo(userDto.getComCode());
			if (null == spComUser && null == branch) {
				sr.setAppFail();
				sr.setResult("上级渠道编码输入有误！");
				return sr;
			}
			if (StringUtils.isNotBlank(userDto.getUpUserCode())) {
				TbSpUser upUser = userDao.findByUserCode(userDto.getUpUserCode());
				if (null == upUser) {
					sr.setFail();
					sr.setResult("未找到关系上属人员!");
					return sr;
				}
			}
			// List<TbSpUser> users = userDao.findByMobile(userDto.getMobile());
			TbSpUser spUser = userDao.findByUserCode(userDto.getUserCode());
			Md5PwdEncoder md5PwdEncoder = new Md5PwdEncoder();
			// if (CollectionUtils.isNotEmpty(users)) {
			if (null != spUser) {
				// spUser = users.get(0);
				if (Constants.TRUE.equals(userDto.getIdType())) {
					List<TbSpUser> numberusers = userDao.findByIdNumber(userDto.getIdNumber());
					if (CollectionUtils.isNotEmpty(numberusers)) {
						for (TbSpUser u : numberusers) {
							if (Constants.USER_REGISTER_TYPE_0.equals(u.getRegisterType())) {
								if (u.getId().compareTo(spUser.getId()) != 0
										&& userDto.getIdNumber().equals(u.getIdNumber())) {
									sr.setFail();
									sr.setResult("您输入的证件号码已被认证!");
									return sr;
								}
							}
						}
					}
				}
				List<TbSpUser> mobileusers = userDao.findByMobile(userDto.getMobile());
				if (CollectionUtils.isNotEmpty(mobileusers)) {
					for (TbSpUser u : mobileusers) {
						if (u.getId().compareTo(spUser.getId()) != 0 && userDto.getMobile().equals(u.getMobile())) {
							sr.setFail();
							sr.setResult("您输入的手机号码已被使用!");
							return sr;
						}
					}
				}
				if (StringUtils.isNotBlank(userDto.getAgrementNo())) {
					// 如果修改了业务关系代码
					if (StringUtils.isNotBlank(spUser.getAgrementNo())
							&& !spUser.getAgrementNo().equals(userDto.getAgrementNo())) {
						String userType = "2";// 默认普通账户 // 已废弃：this.getUserType(orgCode, licenceNo, accType, codeType);
						if (StringUtils.isNotBlank(userDto.getAgrementName())) {
							userType = "3";// 专业代理
						} else {
							// CA协议
							if (StringUtils.isNotBlank(userDto.getOrgCode())
									|| StringUtils.isNotBlank(userDto.getLicenceNo())) {
								userType = "4";// 商户
							} else {
								userType = "5";// 销售人员
								// 临时措施，不送积分
								sr.setFail();
								sr.setResult("当前不支持渠道赠送积分,请更换业务关系代码!");
								return sr;
							}
						}
						userDto.setUserType(userType);
						// 修改其所有子集的业务关系代码
						List<TbSpUser> nextChannels = userDao.findByComCode(spUser.getUserCode());
						if (CollectionUtils.isNotEmpty(nextChannels)) {
							updateNextAgreementNo(userDto, spUser, nextChannels);
						}
						spUser.setChannelCode(userDto.getChannelCode());
						spUser.setChannelName(userDto.getChannelName());
						spUser.setChannelType(userDto.getCustomerType());
						spUser.setCustomName(userDto.getCustomerName());
						spUser.setSaleCode(userDto.getSaleCode());
						spUser.setSaleName(userDto.getSaleName());
						spUser.setAgrementNo(userDto.getAgrementNo());
						spUser.setAgrementName(userDto.getAgrementName());
						List<String> twobs = Lists.newArrayList();
						List<String> backtwobs = findSecondBranch(userDto.getComCode(),twobs);
						if (CollectionUtils.isNotEmpty(backtwobs)) {
							spUser.setBranchCode(backtwobs.get(0));
						}
//						spUser.setBranchCode(userDto.getBranchCode());
						spUser.setAreaCode(null);
						spUser.setAreaName(null);
						spUser.setUserType(userType);
					}

					// if (!userDto.getComCode().startsWith("WX") &&
					// !userDto.getComCode().startsWith("BS")) {
					// spUser.setChannelCode(userDto.getChannelCode());
					// spUser.setChannelName(userDto.getChannelName());
					// spUser.setChannelType(userDto.getCustomerType());
					// spUser.setCustomName(userDto.getCustomerName());
					// spUser.setSaleCode(userDto.getSaleCode());
					// spUser.setSaleName(userDto.getSaleName());
					// spUser.setAgrementNo(userDto.getAgrementNo());
					// spUser.setBranchCode(userDto.getBranchCode());
					// spUser.setAreaCode(null);
					// spUser.setAreaName(null);
					// // 有代理人代码和名称的算中介协议，余下的算CA协议
					// if (StringUtils.isNotBlank(userDto.getAgrementName())) {
					// userType = "3";// 专业代理
					// } else {
					// // CA协议
					// if (StringUtils.isNotBlank(userDto.getOrgCode()) ||
					// StringUtils.isNotBlank(userDto.getLicenceNo())) {
					// userType = "4";// 商户
					// } else {
					// userType = "5";// 销售人员
					// }
					// }
					// } else {
					// List<String> userCodes = Lists.newArrayList();
					// // 找到最顶层渠道
					// List<String> list = this.topUser(userDto.getComCode(), userCodes);
					// TbSpUser topUser = userDao.findByUserCode(list.get(list.size() - 1));
					// spUser.setBranchCode(topUser.getBranchCode());
					// spUser.setAreaCode(topUser.getBranchCode());
					// if (!topUser.getAgrementNo().equals(userDto.getAgrementNo())) {//
					// 与顶级业务关系代码不一样，入库
					// spUser.setChannelCode(userDto.getChannelCode());
					// spUser.setChannelName(userDto.getChannelName());
					// spUser.setChannelType(userDto.getCustomerType());
					// spUser.setCustomName(userDto.getCustomerName());
					// spUser.setSaleCode(userDto.getSaleCode());
					// spUser.setSaleName(userDto.getSaleName());
					// spUser.setAgrementNo(userDto.getAgrementNo());
					// spUser.setBranchCode(userDto.getBranchCode());
					// spUser.setAreaCode(null);
					// spUser.setAreaName(null);
					// // 有代理人代码和名称的算中介协议，余下的算CA协议
					// if (StringUtils.isNotBlank(userDto.getAgrementName())) {
					// userType = "3";// 专业代理
					// } else {
					// // CA协议
					// if (StringUtils.isNotBlank(userDto.getOrgCode()) ||
					// StringUtils.isNotBlank(userDto.getLicenceNo())) {
					// userType = "4";// 商户
					// } else {
					// userType = "5";// 销售人员
					// }
					// }
					// } else {
					// spUser.setChannelCode(null);
					// spUser.setChannelName(null);
					// spUser.setChannelType(null);
					// spUser.setCustomName(null);
					// spUser.setAgrementName(null);
					// spUser.setSaleCode(null);
					// spUser.setSaleName(null);
					// spUser.setAgrementNo(null);
					// }
					// }

				}
				spUser.setComCode(userDto.getComCode());
				spUser.setUpUserCode(userDto.getUpUserCode());
				spUser.setIdType(userDto.getIdType());
				spUser.setMobile(userDto.getMobile());
				spUser.setBaseRate(userDto.getBaseRate());
				spUser.setEmployeeCode(userDto.getEmployeeCode());
				// spUser.setCanModify(userDto.getCanModify());
				// 目前默认不允许修改
				// if (!userDto.getComCode().startsWith("WX") &&
				// !userDto.getComCode().startsWith("BS")) {
				// spUser.setCanModify(Constants.TRUE);
				// }else {
				spUser.setCanModify(Constants.FALSE);
				// }
				spUser.setShopName(userDto.getShopName());
				spUser.setCanScore(userDto.getCanScore());
				spUser.setIdNumber(userDto.getIdNumber());
				// spUser.setRegisterType("1");
				spUser.setUserName(userDto.getUserRealName());
				if (StringUtils.isNotBlank(userDto.getPassword())) {
					spUser.setPassword(md5PwdEncoder.encodePassword(userDto.getPassword()));
				}
				spUser = userDao.save(spUser);
			} else {
				sr.setAppFail();
				sr.setResult("查询渠道用户异常！");
				return sr;
			}
			SysUser sysUser = null;
			SysRoleUser role = null;
			// List<SysUser> dbsysuser = iSysUserDao.findByMobile(userDto.getMobile());
			sysUser = iSysUserDao.findByUserCode(userDto.getUserCode());
			// if (CollectionUtils.isNotEmpty(dbsysuser)) {
			if (null != sysUser) {
				// sysUser = dbsysuser.get(0);
				// if (StringUtils.isNotBlank(userDto.getPassword()) &&
				// StringUtils.isNotBlank(userDto.getOldPassword())) {
				// if
				// (md5PwdEncoder.encodePassword(userDto.getOldPassword()).equals(sysUser.getPassword()))
				// {
				// sysUser.setPassword(md5PwdEncoder.encodePassword(userDto.getPassword()));
				// } else {
				// sr.setFail();
				// sr.setResult("您输入的原始密码错误!");
				// return sr;
				// }
				// }
				if (StringUtils.isNotBlank(userDto.getPassword())) {
					sysUser.setPassword(md5PwdEncoder.encodePassword(userDto.getPassword()));
				}
				// 所属机构
				if (!spUser.getComCode().equals(userDto.getComCode())) {
					if (StringUtils.isNotBlank(userDto.getComCode())
							&& (userDto.getComCode().startsWith("WX") || userDto.getComCode().startsWith("BS"))) {
						List<String> userCodes = Lists.newArrayList();
						List<String> list = findTopBranchNo(userDto.getComCode(), userCodes);
						SysBranch branchs = sysBranchDao.findByBranchNo(list.get(list.size() - 1));
						sysUser.setBranchcode(branchs.getBranchNo());
						sysUser.setBranchName(branchs.getBranchCname());
					} else if (StringUtils.isNotBlank(userDto.getComCode())) {
						SysBranch branchs = sysBranchDao.findByBranchNo(userDto.getComCode());
						sysUser.setBranchcode(branchs.getBranchNo());
						sysUser.setBranchName(branchs.getBranchCname());
					}
				}
				sysUser.setType(userDto.getType());
				sysUser.setClevel(userDto.getRoleType().toString());
				sysUser.setRoleCode(userDto.getRoleType().toString());
				sysUser.setMobileno(userDto.getMobile());
				role = roleUserDao.findByUserid(sysUser.getUserid());
				if (null == role) {
					role = new SysRoleUser();
					role.setRoleid(userDto.getRoleType());
				} else {
					// 职级是否变更
					if (role.getRoleid() != userDto.getRoleType()
							&& StringUtils.isNotBlank(userDto.getRankChangeType())) {
						TbSpRankChange rank = new TbSpRankChange();
						rank.setChangeTime(new Date());
						rank.setUserCode(userDto.getUserCode());
						rank.setOldRank(role.getRoleid().toString());
						rank.setNewRank(userDto.getRoleType().toString());
						rank.setChangeType(userDto.getRankChangeType());
						rankChangeDao.save(rank);
					}
					role.setRoleid(userDto.getRoleType());
				}
			} else {
				sr.setAppFail();
				sr.setResult("查询渠道用户异常！");
				return sr;
			}
			roleUserDao.save(role);
			iSysUserDao.save(sysUser);
		} catch (Exception e) {
			e.printStackTrace();
			sr.setAppFail();
			sr.setResult("修改信渠道用户息失败！");
			return sr;
		}
		sr.setSuccess();
		return sr;
	}

	@Override
	public ServiceResult nextChannelList(String mobile, String istopUser, String branchNo, String channelId,
			String shopName, Integer pageSize, Integer pageNumber) {

		ServiceResult sr = new ServiceResult();

		StringBuilder sql = new StringBuilder();
		List<Map<String, Object>> list = null;
		Map<String, Object> paramMap = new HashMap<String, Object>();
		sql.append("select  u.* from tb_sp_user u ");
		// 条件
		sql.append(" where u.state =1 ");
		if (StringUtils.isNotEmpty(branchNo)) {
			if (!branchNo.equals("0000")) {
				sql.append(" and u.COM_CODE = :comCode ");
				paramMap.put("comCode", branchNo);
			} else {
				sql.append(" and u.REGISTER_TYPE in('1','2') ");
			}
		} else {
			paramMap.put("comCode", "branchNo");
		}
		if (StringUtils.isNotEmpty(channelId)) {
			sql.append(" and u.USER_CODE = :userCode ");
			paramMap.put("userCode", channelId);
		}
		if (StringUtils.isNotEmpty(istopUser)) {
			if ("top".equals(istopUser)) {
				sql.append(" and substring(COM_CODE,1,2)!='WX' and substring(COM_CODE,1,2)!='BS' ");
			} else {
				sql.append(" and (substring(COM_CODE,1,2)='WX' or substring(COM_CODE,1,2)='BS' )");
			}
		}
		if (StringUtils.isNotEmpty(mobile)) {
			sql.append(" and u.MOBILE = :mobile ");
			paramMap.put("mobile", mobile);
		}
		if (StringUtils.isNotEmpty(shopName)) {
			sql.append(" and u.SHOP_NAME = :shopName ");
			paramMap.put("shopName", shopName);
		}
		sql.append(" order by u.ID asc ");
		list = readJdbcTemplate2.queryForList(sql.toString(), paramMap);
		List<TbSpUser> returnList = Lists.newArrayList();
		for (int i = 0; i < list.size(); i++) {// 遍历设置实体
			TbSpUser user = new TbSpUser();
			user.setId((Integer) list.get(i).get("ID"));
			user.setUserCode((String) list.get(i).get("USER_CODE"));
			user.setUserCodeBs((String) list.get(i).get("USER_CODE_BS"));
			user.setUserName((String) list.get(i).get("USER_NAME"));
			user.setNickName((String) list.get(i).get("NICK_NAME"));
			user.setMobile((String) list.get(i).get("MOBILE"));
			user.setIdNumber((String) list.get(i).get("ID_NUMBER"));
			user.setChannelType((String) list.get(i).get("CHANNEL_TYPE"));
			user.setChannelName((String) list.get(i).get("CHANNEL_NAME"));
			user.setAgrementName((String) list.get(i).get("AGREMENT_NAME"));
			user.setBranchCode((String) list.get(i).get("BRANCH_CODE"));
			user.setComCode((String) list.get(i).get("COM_CODE"));
			user.setSaleCode((String) list.get(i).get("SALE_CODE"));
			user.setSaleName((String) list.get(i).get("SALE_NAME"));
			user.setChannelCode((String) list.get(i).get("CHANNEL_CODE"));
			user.setCustomName((String) list.get(i).get("CUSTOM_NAME"));
			user.setShopName((String) list.get(i).get("SHOP_NAME"));
			user.setStoreCreateTime((Timestamp) list.get(i).get("STORE_CREATE_TIME"));
			user.setAgrementNo((String) list.get(i).get("AGREMENT_NO"));
			user.setState((String) list.get(i).get("STATE"));
			user.setIdType((String) list.get(i).get("ID_TYPE"));
			user.setCanModify((String) list.get(i).get("CAN_MODIFY"));
			user.setCanScore((String) list.get(i).get("CAN_SCORE"));
			user.setStoreFlag((String) list.get(i).get("STORE_FLAG"));
			user.setRegisterType((String) list.get(i).get("REGISTER_TYPE"));
			user.setBaseRate((Double) list.get(i).get("BASE_RATE"));
			user.setState((String) list.get(i).get("STATE"));
			user.setUserType((String) list.get(i).get("USER_TYPE"));
			user.setUpUserCode((String) list.get(i).get("UP_USERCODE"));
			user.setEmployeeCode((String) list.get(i).get("EMPLOYEE_CODE"));
			returnList.add(user);
			// List<TbSpUser> newList = Lists.newArrayList();
			// returnList.addAll(allUserRecursive(user, newList));
		}

		// List<TbSpUser> newList = null;
		// if (StringUtils.isNotEmpty(channelId) || StringUtils.isNotEmpty(shopName)) {
		// newList = Lists.newArrayList();
		// for (TbSpUser user : returnList) {
		// if (StringUtils.isNotEmpty(channelId) && StringUtils.isNotEmpty(shopName)) {
		// if (channelId.equals(user.getUserCode()) &&
		// shopName.equals(user.getShopName())) {
		// newList.add(user);
		// }
		// } else if (StringUtils.isNotEmpty(channelId)) {
		// if (channelId.equals(user.getUserCode())) {
		// newList.add(user);
		// }
		// } else if (StringUtils.isNotEmpty(shopName)) {
		// if (shopName.equals(user.getShopName())) {
		// newList.add(user);
		// }
		// }
		// }
		// } else {
		// newList = returnList;
		// }
		Integer startPageNumber = (pageNumber - 1) * pageSize;
		Integer endPageNumber = pageNumber * pageSize;
		Integer size = returnList.size();
		List<TbSpUser> backList = returnList.subList(startPageNumber <= size ? startPageNumber : size,
				endPageNumber <= size ? endPageNumber : size);

		for (TbSpUser user : backList) {
			TbSpUser upUser = userDao.findByUserCode(user.getComCode());
			if (null != upUser) {
				user.setRefereeUser(upUser);// 上级是用户
			} else {// 上级是机构
				TbSpUser upBranch = new TbSpUser();
				SysBranch branch = sysBranchDao.findByBranchNo(user.getComCode());
				if (null != branch) {
					upBranch.setUserCode(branch.getBranchNo());
					upBranch.setShopName(branch.getBranchCname());
					user.setRefereeUser(upBranch);
				}
			}
			SysUser sysUser = iSysUserDao.findByUserCode(user.getUserCode());
			if (null != sysUser) {
				user.setSysUser(sysUser);
			}
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("list", backList);
		map.put("total", size);
		sr.setResult(map);
		return sr;
	}

	public List<TbSpUser> allUserRecursive(TbSpUser user, List<TbSpUser> newList) {
		List<TbSpUser> users = userDao.findByComCode(user.getUserCode());
		if (CollectionUtils.isNotEmpty(users)) {
			newList.addAll(users);
			for (TbSpUser u : users) {
				log.info(u.getUserCode());
				allUserRecursive(u, newList);
			}
		}
		return newList;
	}

	@Override
	public ServiceResult treeNextChannelList(String businessNo, String type) {
		ServiceResult sr = new ServiceResult();
		if (StringUtils.isNotBlank(type) && "level".equals(type)) {
			List<TbSpUser> users = userDao.findByComCode(businessNo);
			sr.setResult(users);
		} else if (StringUtils.isNotBlank(type) && "order".equals(type)) {

			List<TbSpUser> users = Lists.newArrayList();
			List<SysBranch> branchs = sysBranchDao.findNextBranch(businessNo);
			for (SysBranch branch : branchs) {
				TbSpUser user = new TbSpUser();
				user.setShopName(branch.getBranchCname());
				user.setUserCode(branch.getBranchNo());
				users.add(user);
			}
			List<TbSpUser> dbuser = userDao.findByComCode(businessNo);
			if (CollectionUtils.isNotEmpty(dbuser)) {
				users.addAll(dbuser);
			}
			sr.setResult(users);
		}
		return sr;
	}

	@Override
	public ServiceResult nextBranchList(String branchNo, String nextBranchNo, String nextBranchName, int pageNumber,
			int pageSize) {
		ServiceResult sr = new ServiceResult();
		// List<SysBranch> branchs = sysBranchDao.findNextBranch(businessNo);
		// sr.setResult(branchs);

		Sort sort = new Sort(Direction.ASC, "branchNo");
		Page<SysBranch> page = sysBranchDao.findAll(new Specification<SysBranch>() {
			public Predicate toPredicate(Root<SysBranch> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicate = new ArrayList<Predicate>();
				if (StringUtils.isNotEmpty(branchNo)) {
					log.info(branchNo);
					predicate.add(cb.equal(root.get("upperBranchNo").as(String.class), branchNo));
				} else {
					predicate.add(cb.equal(root.get("upperBranchNo").as(String.class), "0000"));
				}
				if (StringUtils.isNotEmpty(nextBranchNo)) {
					log.info(nextBranchNo);
					predicate.add(cb.equal(root.get("branchNo").as(String.class), nextBranchNo));
				}
				if (StringUtils.isNotEmpty(nextBranchName)) {
					log.info(nextBranchName);
					predicate.add(cb.like(root.get("branchCname").as(String.class), "%" + nextBranchName + "%"));
				}

				predicate.add(cb.equal(root.get("validStatus").as(String.class), "1"));
				Predicate[] pre = new Predicate[predicate.size()];
				return query.where(predicate.toArray(pre)).getRestriction();
			}
		}, PageRequest.of(pageNumber - 1, pageSize, sort));
		sr.setResult(page);
		return sr;
	}

	@Override
	public ServiceResult thisChannel(String code) {
		ServiceResult sr = new ServiceResult();
		if (code.startsWith("WX") || code.startsWith("BS")) {
			TbSpUser user = userDao.findByUserCode(code);
			if (null != user) {
				TbSpUser upUser = userDao.findByUserCode(user.getComCode());
				if (null != upUser) {
					user.setRefereeUser(upUser);// 上级是用户
				} else {// 上级是机构
					TbSpUser upBranch = new TbSpUser();
					SysBranch branch = sysBranchDao.findByBranchNo(user.getComCode());
					if (null != branch) {
						upBranch.setUserCode(branch.getBranchNo());
						upBranch.setShopName(branch.getBranchCname());
						user.setRefereeUser(upBranch);
					}
				}
			}
			sr.setResult(user);
		} else {
			sr.setResult(sysBranchDao.findByBranchNo(code));
		}
		return sr;
	}

	@Override
	public ServiceResult authUserList(String userId, String mobile, String type, int pageNumber, int pageSize) {
		ServiceResult sr = new ServiceResult();
		Sort sort = new Sort(Direction.DESC, "userid");
		Page<SysUser> page = iSysUserDao.findAll(new Specification<SysUser>() {
			public Predicate toPredicate(Root<SysUser> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicate = new ArrayList<Predicate>();
				if (StringUtils.isNotEmpty(userId)) {
					log.info(userId);
					predicate.add(cb.equal(root.get("userid").as(String.class), userId));
				}
				if (StringUtils.isNotEmpty(mobile)) {
					log.info(mobile);
					predicate.add(cb.equal(root.get("mobileno").as(String.class), mobile));
				}
				if (StringUtils.isNotEmpty(type)) {
					log.info(type);
					predicate.add(cb.equal(root.get("type").as(String.class), type));
				}
				predicate.add(cb.equal(root.get("status").as(String.class), "1"));
				Predicate[] pre = new Predicate[predicate.size()];
				return query.where(predicate.toArray(pre)).getRestriction();
			}
		}, PageRequest.of(pageNumber - 1, pageSize, sort));
		sr.setResult(page);
		return sr;
	}

	@Override
	public ServiceResult orderAuth(String userid, String type) {
		ServiceResult sr = new ServiceResult();
		List<SysBranch> returnBranch = Lists.newArrayList();
		List<TbSpAuthority> authList = authorityDao.findByUserCode(userid);
		if (CollectionUtils.isNotEmpty(authList)) {// 配置过
			for (TbSpAuthority auth : authList) {
				if (auth.getChannelCode().startsWith("WX") || auth.getChannelCode().startsWith("BS")) {
					SysBranch recursiveBranch = new SysBranch();
					if ("order".equals(type)) {
						TbSpUser user = userDao.findByUserCode(auth.getChannelCode());
						recursiveBranch.setBranchNo(user.getUserCode());
						recursiveBranch.setBranchCname(user.getShopName());
					} else {
						SysBranch backBranch = this.authRecursive(auth.getChannelCode());
						recursiveBranch.setBranchCname(backBranch.getBranchCname());
						recursiveBranch.setBranchNo(backBranch.getBranchNo());
						recursiveBranch.setNextBranch(backBranch.getNextBranch());
						recursiveBranch.setAddressCname(backBranch.getAddressCname());
						recursiveBranch.setPhoneNumber(backBranch.getPhoneNumber());
						recursiveBranch.setUpperBranchNo(backBranch.getUpperBranchNo());
						recursiveBranch.setBranchType(backBranch.getBranchType());
						recursiveBranch.setBranchLevel(backBranch.getBranchLevel());
						recursiveBranch.setValidStatus(backBranch.getValidStatus());
						log.info("recursiveBranch----{}", backBranch.getNextBranch().toString());
					}
					returnBranch.add(recursiveBranch);
				} else {
					SysBranch branch = sysBranchDao.findByBranchNo(auth.getChannelCode());
					returnBranch.add(branch);
				}
			}
		}
		sr.setResult(returnBranch);
		return sr;
	}

	public SysBranch authRecursive(String code) {
		List<String> userCodes = Lists.newArrayList();
		List<String> list = Lists.newArrayList();
		list.add(code);
		list.addAll(findTopBranchNo(code, userCodes));
		int lastOne = list.size() - 1;
		String branchno = list.get(lastOne);
		SysBranch branch = sysBranchDao.findByBranchNo(branchno);
		List<SysBranch> branchs = Lists.newArrayList();
		branchs.add(branch);
		for (int i = lastOne - 1; i >= 0; i--) {
			SysBranch newbranch = new SysBranch();
			TbSpUser user = userDao.findByUserCode(list.get(i));
			newbranch.setBranchNo(user.getUserCode());
			newbranch.setBranchCname(user.getShopName());
			branchs.add(newbranch);
		}
		for (int i = 0; i < branchs.size(); i++) {
			if (i + 1 <= branchs.size() - 1) {
				List<SysBranch> newbranchs = Lists.newArrayList();
				newbranchs.add(branchs.get(i + 1));
				branchs.get(i).setNextBranch(newbranchs);
			}
		}
		log.info(branchs.get(0).getNextBranch().toString());
		return branchs.get(0);
	}

	public List<String> findTopBranchNo(String number, List<String> upNumbers) {
		TbSpUser user = userDao.findByUserCode(number);
		SysBranch branch = sysBranchDao.findByBranchNo(user.getComCode());
		if (null != user && null == branch) {
			upNumbers.add(user.getComCode());
			findTopBranchNo(user.getComCode(), upNumbers);
		} else if (null != user && null != branch) {
			upNumbers.add(branch.getBranchNo());
		}
		return upNumbers;
	}

	public List<String> findAllTopBranchNo(String number, List<String> upNumbers) {
		TbSpUser user = userDao.findByUserCode(number);
		if (null != user) {
			upNumbers.add(user.getComCode());
			findAllTopBranchNo(user.getComCode(), upNumbers);
		} else {
			SysBranch branch = sysBranchDao.findByBranchNo(number);
			if (null != branch && !branch.getBranchNo().equals("0000")) {
				upNumbers.add(branch.getUpperBranchNo());
				findAllTopBranchNo(branch.getUpperBranchNo(), upNumbers);
			}
		}
		return upNumbers;
	}

	public Set<String> findAllNextBranchNo(Set<String> upNumbers, Set<String> returnNums) {

		for (String sl : upNumbers) {
			Set<String> newset = new HashSet();
			List<TbSpUser> users = userDao.findByComCode(sl);
			if (CollectionUtils.isNotEmpty(users)) {
				for (TbSpUser u : users) {
					returnNums.add(u.getUserCode());
					newset.add(u.getUserCode());
				}
			}
			List<SysBranch> branchs = sysBranchDao.findNextBranch(sl);
			if (CollectionUtils.isNotEmpty(branchs)) {
				for (SysBranch branch : branchs) {
					returnNums.add(branch.getBranchNo());
					newset.add(branch.getBranchNo());
				}
			}
			if (CollectionUtils.isNotEmpty(newset)) {
				findAllNextBranchNo(newset, returnNums);
			}
		}
		return returnNums;
	}

	@Transactional
	@Override
	public ServiceResult updateOrderAuth(String[] list, String userCode) {

		ServiceResult sr = new ServiceResult();
		authorityDao.deleteByUserCode(userCode);
		List<String> authList = Lists.newArrayList();
		for (String branchNo : list) {
			List<String> userCodes = Lists.newArrayList();
			List<String> upnumbers = this.findAllTopBranchNo(branchNo, userCodes);
			List<String> contain = ListUtil.listContainAnyOne(authList, upnumbers);
			if (CollectionUtils.isEmpty(contain)) {
				authList.add(branchNo);
			}
		}
		for (String branchNo : authList) {
			List<String> userCodes = Lists.newArrayList();
			List<String> upnumbers = this.findAllTopBranchNo(branchNo, userCodes);
			List<String> contain = ListUtil.listContainAnyOne(authList, upnumbers);
			if (CollectionUtils.isNotEmpty(contain)) {
				for (String c : contain) {
					authorityDao.deleteByUserCodeAndChannelCode(userCode, c);
				}
			} else {
				TbSpAuthority newAuth = new TbSpAuthority();
				newAuth.setChannelCode(branchNo);
				newAuth.setCreateTime(new Date());
				newAuth.setUserCode(userCode);
				newAuth.setStatus(Constants.TRUE);
				authorityDao.save(newAuth);
			}
		}
		return sr;
	}

	@Override
	public ServiceResult topChannelUser(String userCode) {
		ServiceResult sr = new ServiceResult();
		List<String> userCodes = Lists.newArrayList();
		TbSpUser user = userDao.findByUserCode(userCode);
		userCodes.add(userCode);
		if (StringUtils.isNotBlank(user.getComCode())) {
			List<String> list = this.topUser(user.getComCode(), userCodes);
			TbSpUser topuser = userDao.findByUserCode(list.get(list.size() - 1));
			sr.setResult(topuser);
		} else {
			sr.setFail();
			sr.setResult("找不到上级渠道！");
		}

		return sr;
	}

	public List<String> topUser(String userCode, List<String> upNumbers) {

		TbSpUser user = userDao.findByUserCode(userCode);
		if (null != user) {
			upNumbers.add(user.getUserCode());
			topUser(user.getComCode(), upNumbers);
		}
		return upNumbers;
	}

	@Override
	public ServiceResult isHasIdnumber(String idNumber) {
		ServiceResult sr = new ServiceResult();
		List<TbSpUser> dbusers = userDao.findByIdNumber(idNumber);
		if (CollectionUtils.isNotEmpty(dbusers)) {
			for (TbSpUser u : dbusers) {
				if (!Constants.USER_REGISTER_TYPE_1.equals(u.getRegisterType())) {
					if (idNumber.equals(u.getIdNumber())) {
						sr.setFail();
						sr.setResult("温馨提示 : 您输入的证件号码已被认证!");
						return sr;
					}
				}
			}
		}
		return sr;
	}

	// 修改下级业务关系代码
	public void updateNextAgreementNo(UserDto userDto, TbSpUser oldUser, List<TbSpUser> upNumbers) {

		for (TbSpUser u : upNumbers) {
			List<TbSpUser> newset = userDao.findByComCode(u.getUserCode());
			// 判断是否与修改的一样
			// if (u.getAgrementNo().equals(oldUser.getAgrementNo())) {
			u.setChannelCode(userDto.getChannelCode());
			u.setChannelName(userDto.getChannelName());
			u.setChannelType(userDto.getCustomerType());
			u.setCustomName(userDto.getCustomerName());
			u.setSaleCode(userDto.getSaleCode());
			u.setSaleName(userDto.getSaleName());
			u.setAgrementNo(userDto.getAgrementNo());
			u.setBranchCode(userDto.getBranchCode());
			u.setUserType(userDto.getUserType());
			userDao.save(u);
			// newset.add(u);
			// }
			if (CollectionUtils.isNotEmpty(newset)) {
				updateNextAgreementNo(userDto, oldUser, newset);
			}
		}

	}

	@Override
	public ServiceResult setShopPro(StoreRateReq store) {
		ServiceResult sr = new ServiceResult();
		String userCode = store.getUserCodes();
		storeProductDao.deleteByUserCode(userCode);
		topChannelAuthProductDao.deleteByUserCode(userCode);
		List<Integer> productIds = Lists.newArrayList();
		for (TbSpStoreConfig conf : store.getStoreConfig()) {
			TbSpStoreProduct newStoreP = new TbSpStoreProduct();
			Integer productId = conf.getProductId();
			productIds.add(productId);
			newStoreP.setIsShow(Constants.TRUE);
			newStoreP.setProductId(productId);
			newStoreP.setUserCode(userCode);
			Integer maxNo = storeProductDao.findMaxSerialNoByUser(userCode);
			if (null != maxNo) {
				newStoreP.setSerialNo(maxNo + 1);
				newStoreP.setRiskSerialNo(maxNo + 1);
			} else {
				newStoreP.setSerialNo(1);
				newStoreP.setRiskSerialNo(1);
			}
			storeProductDao.save(newStoreP);
			// }
			// 添加到授权表
			TbSpTopChannelAuthProduct authProduct = new TbSpTopChannelAuthProduct();
			authProduct.setUserCode(userCode);
			authProduct.setProductId(productId);
			authProduct.setProductCname(conf.getProductName());
			authProduct.setProductEname(conf.getProductEname());
			topChannelAuthProductDao.save(authProduct);
		}
		// 添加下级所有渠道的产品
		List<TbSpUser> newset = userDao.findByComCode(userCode);
		nextChannelStorePro(productIds, newset);
		return sr;
	}

	// 添加下级所有渠道的产品
	public void nextChannelStorePro(List<Integer> productIds, List<TbSpUser> upNumbers) {
		for (TbSpUser u : upNumbers) {
			String userCode = u.getUserCode();
			storeProductDao.deleteByUserCode(userCode);
			List<TbSpUser> newset = userDao.findByComCode(userCode);
			for (Integer productId : productIds) {
				TbSpStoreProduct dbp = storeProductDao.findByUCodeAndPId(userCode, productId);
				if (null == dbp) {
					TbSpStoreProduct newStoreP = new TbSpStoreProduct();
					newStoreP.setIsShow(Constants.TRUE);
					newStoreP.setProductId(productId);
					newStoreP.setUserCode(userCode);
					Integer maxNo = storeProductDao.findMaxSerialNoByUser(userCode);
					if (null != maxNo) {
						newStoreP.setSerialNo(maxNo + 1);
						newStoreP.setRiskSerialNo(maxNo + 1);
					} else {
						newStoreP.setSerialNo(1);
						newStoreP.setRiskSerialNo(1);
					}
					storeProductDao.save(newStoreP);
				}
			}
			if (CollectionUtils.isNotEmpty(newset)) {
				nextChannelStorePro(productIds, newset);
			}
		}

	}

	@Override
	public ServiceResult branchManage(SysBranch sysBranch) {
		ServiceResult sr = new ServiceResult();
		if ("add".equals(sysBranch.getAddOrUpdate())) {
			// 生成机构编码
			String max = sysBranchDao.findMaxBranchNo(sysBranch.getUpperBranchNo());
			if (StringUtils.isNotBlank(max)) {
				String newNo = max.substring(0, max.length() - 4)
						+ String.valueOf(Integer.parseInt(max.substring(max.length() - 4, max.length())) + 1);
				sysBranch.setBranchNo(newNo);
			} else {
				if ("0000".equals(sysBranch.getUpperBranchNo())) {
					sysBranch.setBranchNo("1000");
				} else {
					sysBranch.setBranchNo(sysBranch.getUpperBranchNo() + "1000");
				}
			}
			SysBranch updb = sysBranchDao.findByBranchNo(sysBranch.getUpperBranchNo());
			sysBranch.setBranchLevel(String.valueOf(Integer.parseInt(updb.getBranchLevel()) + 1));

		} else {
			SysBranch db = sysBranchDao.findByBranchNo(sysBranch.getBranchNo());
			if (!db.getUpperBranchNo().equals(sysBranch.getUpperBranchNo())) {
				SysBranch updb = sysBranchDao.findByBranchNo(sysBranch.getUpperBranchNo());
				if (null == updb) {
					sr.setFail();
					sr.setResult("不存在该上级机构，请确认！");
					return sr;
				} else {
					sysBranch.setBranchLevel(String.valueOf(Integer.parseInt(updb.getBranchLevel()) + 1));
				}
			}
		}
		sysBranchDao.save(sysBranch);
		return sr;
	}

	@Override
	public ServiceResult treeNextBranchList(String branchNo) {
		ServiceResult sr = new ServiceResult();
		List<SysBranch> branchs = sysBranchDao.findNextBranch(branchNo);
		sr.setResult(branchs);
		return sr;
	}

}
